import 'dart:convert';

import 'package:device_calendar/device_calendar.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_timezone/flutter_timezone.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:photo_frame/main.dart';
import 'package:photo_frame/net/model/event_dto.dart';
import 'package:photo_frame/user/user_manager.dart';
import 'package:photo_frame/utils/a_logger.dart';
import 'package:photo_frame/utils/color_util.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'dart:io' as io;

class CalendarHelper {
  DeviceCalendarPlugin _deviceCalendarPlugin = DeviceCalendarPlugin();
  List<Calendar>? _calendars;

  List<Calendar>? get calendars => _calendars;

  CalendarHelper._();

  static final CalendarHelper _instance = CalendarHelper._();

  static CalendarHelper get instance => _instance;

  // Future<String?> createOrUpdateEvent(EventDTO originEvent) async {
  //   var cloneEvent = originEvent.copyWithMap();
  //   if (io.Platform.isIOS) {
  //     cloneEvent.attendees = null;
  //   }
  //   return _deviceCalendarPlugin
  //       .hasPermissions()
  //       .then<Result<bool>>((permissionsGranted) {
  //         if (!isPermissionGranted(permissionsGranted)) {
  //           return _deviceCalendarPlugin.requestPermissions();
  //         }
  //         return Result<bool>()..data = true;
  //       })
  //       .then((permissionsGranted) {
  //         if (!isPermissionGranted(permissionsGranted)) {
  //           throw FormatException(
  //               "createOrUpdateEvent permissionsGranted :false");
  //         }
  //         return true;
  //       })
  //       .then<Calendar?>((e) => findCalendar())
  //       .then<String?>((fotocubeCalendar) {
  //         ALogger.e(
  //             "fotocubeCalendar find res : ${fotocubeCalendar?.toJson()}");
  //         if (fotocubeCalendar == null) {
  //           var calendarName = fotocubeCalendarDisplayName();
  //           var calendarColor = Colors.red;
  //           // UserManager.instance.getAvatarColor()?.toColor()
  //           var accountName = UserManager.instance.getEmail();
  //           return _deviceCalendarPlugin
  //               .createCalendar(calendarName,
  //                   localAccountName: accountName, calendarColor: calendarColor)
  //               .then((e) {
  //             _calendars?.add(Calendar(
  //                 id: e.data,
  //                 name: calendarName,
  //                 accountName: accountName,
  //                 color: calendarColor.value));
  //             ALogger.e(
  //                 "createCalendar : ${e.isSuccess} ${e.data} ${e?.errors?.map((e) => e.errorMessage).toList()}");
  //             return e.data;
  //           });
  //         }
  //         return fotocubeCalendar.id;
  //       })
  //       .then((calendarId) async {
  //         if (calendarId == null) {
  //           throw FormatException(
  //               "createOrUpdateEvent createCalendar failed （platform nosupport）!!!!!");
  //         }
  //         // ALogger.e(
  //         //     "createCalendar : calendarId-${calendarId}  event-${cloneEvent}");
  //         var transformEvent = await transform(calendarId, cloneEvent);
  //         ALogger.i("transform : ${transformEvent.toJson()}");
  //         return _deviceCalendarPlugin
  //             .createOrUpdateEvent(transformEvent)
  //             .then((createRes) {
  //           ALogger.e(
  //               "createOrUpdateEvent : ${createRes?.isSuccess} ${createRes?.data} ${createRes?.errors?.map((e) => e.errorMessage).toList()}");
  //           // _deviceCalendarPlugin
  //           //     .retrieveEvents(
  //           //         calendarId,
  //           //         RetrieveEventsParams(
  //           //             startDate: DateTime(1000),
  //           //             endDate: DateTime.now().add(Duration(days: 100))))
  //           //     .then((e) {
  //           //   ALogger.e(
  //           //       "createOrUpdateEvent  query: ${e.isSuccess} ${e.data?.where((e) => e.eventId == createRes?.data).map((e) => e.toJson()).toList()} ${e?.errors?.map((e) => e.errorMessage).toList()}");
  //           // });
  //           return createRes;
  //         }).then((e) => e?.data);
  //       })
  //       .catchError((_) {
  //         throw _;
  //         // print(_);
  //         // ALogger.e("createOrUpdateEvent $_");
  //         // return null;
  //       });
  // }

  // Future<bool?> deleteEvent(EventDTO event) async {
  //   var calendar = findCalendar();
  //   if (calendar == null) {
  //     return false;
  //   }
  //   await _deviceCalendarPlugin
  //       .deleteEvent(calendar.id, event.event_id?.toString())
  //       .then((e) => e.data)
  //       .whenComplete(() {
  //     findCalendar()?.id;
  //   });
  // }

  // Calendar? findCalendar() {
  //   ALogger.e("findCalendar : ${_calendars?.map((e) => e.name).toList()} ");
  //   try {
  //     return _calendars!
  //         .where((e) =>
  //             e.isFotocube() || (e.isDefault == true && e.isReadOnly != true))
  //         .firstOrNull;
  //   } catch (_) {
  //     print("findCalendar not found ${_}");
  //   }
  //   return null;
  // }

  /// ios
  ///    iCloud : calendars {id: 1D7ED0F3-990D-435A-B3B4-61C51198CF63, name: 日历, isReadOnly: false, isDefault: false, color: 4279938552, accountName: iCloud, accountType: CalDAV}
  ///    Gmail : calendars {id: B401B4A0-706B-4615-A62E-4E1AD9DECA80, name: ffffgggg@gmail.com, isReadOnly: false, isDefault: true, color: 4279938552, accountName: Gmail, accountType: CalDAV}
  ///    Outlook :  {id: 3E1529D9-E4BA-4177-9406-B13C65B49EBB, name: 中国 节假日, isReadOnly: false, isDefault: false, color: 4284734007, accountName: Outlook, accountType: Exchange}
  ///    other :calendars {id: 4D325AF3-4984-498A-989D-8CFB60195BC8, name: 中国大陆节假日, isReadOnly: true, isDefault: false, color: 4294939904, accountName: Subscribed Calendars, accountType: Subscribed}
  ///
  ///    Gmail :calendars {id: 4, name: gggf@gmail.com, isReadOnly: false, isDefault: true, color: -509406, accountName: ffffgggg@gmail.com, accountType: com.google}
  ///    Outlook : calendars {id: 5, name: Calendar, isReadOnly: false, isDefault: true, color: -3200202, accountName: ffffgggg@outlook.com, accountType: com.microsoft.office.outlook.USER_ACCOUNT}
  ///    other : calendars {id: 3, name: Samsung Calendar, isReadOnly: false, isDefault: true, color: -16759123, accountName: 8615221333203, accountType: com.osp.app.signin}
  Future<List<Calendar>?> retrieveCalendars({bool? force}) {
    if (force != true && calendars?.isNotEmpty == true) {
      return Future.value(calendars);
    }
    return _deviceCalendarPlugin
        .hasPermissions()
        .then((permissionsGranted) async {
      isPermissionGranted(Result<bool> res) {
        print("retrieveCalendars  isPermissionGranted ${res.data == true}");
        return res.isSuccess && res.data == true;
      }

      if (!isPermissionGranted(permissionsGranted)) {
        permissionsGranted = await _deviceCalendarPlugin.requestPermissions();
        if (!isPermissionGranted(permissionsGranted)) {
          Fluttertoast.showToast(
              msg: AppLocalizationsWrapper.instance
                  .unwrap(App.globalCxt)
                  .importSchedulePermissionsGranted);
          return null;
        }
      }
      var calendars = (await _deviceCalendarPlugin.retrieveCalendars()).data
          as List<Calendar>?;
      print("retrieveCalendars ${calendars?.map((e) => e.accountName).toList()}");
      print(
          "retrieveCalendars calendars.length ${calendars?.length.toString() ?? 0}");
      return calendars;
    }).then((e) {
      _calendars = e?.toList();
      return e;
    }).catchError((e) {
      ALogger.e(e);
    });
  }

  transform(String calendarId, EventDTO eventDTO) async {
    String _timezone = 'Etc/UTC';
    try {
      _timezone = await FlutterTimezone.getLocalTimezone();
    } catch (e) {
      print('Could not get the local timezone');
    }
    TZDateTime? _startDate;
    TZDateTime? _endDate;

    var currentLocation = timeZoneDatabase.locations[_timezone];
    if (currentLocation != null) {
      _startDate = TZDateTime.fromMillisecondsSinceEpoch(currentLocation,
          eventDTO.dtstart ?? DateTime.now().millisecondsSinceEpoch);
      _endDate = TZDateTime.fromMillisecondsSinceEpoch(currentLocation,
          eventDTO.dtend ?? DateTime.now().millisecondsSinceEpoch);
    } else {
      var fallbackLocation = timeZoneDatabase.locations['Etc/UTC'];
      _startDate = TZDateTime.now(fallbackLocation!);
      _endDate = TZDateTime.now(fallbackLocation);
    }
    // ALogger.e("transform- eventDTO.reminder: ${eventDTO.reminder} ");
    return Event(calendarId,
        eventId: eventDTO.event_id?.toString(),
        title: eventDTO.title,
        start: _startDate,
        end: _endDate,
        description: eventDTO.description,
        attendees: eventDTO.attendees
            ?.split(',')
            .map((e) => Attendee(emailAddress: e, role: AttendeeRole.None))
            .toList(),
        recurrenceRule: eventDTO.toRecurrenceRule(),
        reminders: [Reminder(minutes: 0)],
        // reminders: eventDTO.reminder?.trim().isNotEmpty == true
        //     ? eventDTO.reminder!
        //         .split(',')
        //         .map((e) => Reminder(minutes: int.tryParse(e)))
        //         .toList()
        //     : null,
        location: _timezone,
        allDay: eventDTO.allDay == 1,
        status: EventStatus.None);
  }
}

isPermissionGranted(Result<bool> res) {
  print("isPermissionGranted ${res.data == true}");
  return res.isSuccess && res.data == true;
}
